package user

import (
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	g "gogame/game"
	cfg "gogame/game/manage/config/structs"
	"gogame/game/manage/module"
	"gogame/game/module/base"
	"gogame/gameservice/worker"
	"gogame/lib/timer"
	"gogame/pb"
)

type ModuleUser struct {
	*base.ModuleBase
	Api
}

var User *ModuleUser

func init() {
	User = &ModuleUser{
		ModuleBase: base.NewModuleBase(),
	}
	// 手动定义接口 手动定义的接口args是any类型
	User.Api2Func = worker.Api2FuncInfo{
		// key：接口名，需要驼峰，和反射调用保持一致 value: [接口func，接口args]
		"GetInfo": worker.FmtFuncInfo(User.GetInfo, new(pb.UserGetInfoArgs)),
	}

	_moduleName := "user"
	// 路由注册 未定义Api2Func默认采用反射筛选符合条件的方法注册和调用
	worker.Register(_moduleName, User)
	// 模块注册
	module.Manage.User = User
	// 定时器注册 测试
	_name2Func := timer.Api2Func{
		// key就是定时器文件名 values定时器方法名
		"timer_hello": TimerHello,
	}
	timer.Register(_moduleName, _name2Func)

}

// CreateUser 创建玩家
func (m *ModuleUser) CreateUser(bindUid, ip string, sid int64, gatewayUrl string) *pb.ModelUser {
	_nt := g.C.Now()
	_objectId := g.C.GetObjectId()
	_uid := fmt.Sprintf("%d_%s", sid, _objectId)
	_userInfo := &pb.ModelUser{
		Id:            _objectId,
		Uid:           _uid,
		UUid:          g.C.GetUUidByMongoId(_objectId),
		Sid:           sid,
		BindUid:       bindUid,
		ExtServerName: "",
		Name:          _objectId,
		Ctime:         _nt,
		LoginTime:     _nt,
		CreateIp:      ip,
		LastLoginIp:   ip,
		Lt:            _nt,
		LoginNum:      1, // 新号默认已登录1天
		Lv:            1, // 新号等级默认1级
	}

	// 插入玩家数据 这里实时插入
	g.Mdb.InsertOne("userinfo", _userInfo)
	// 载入redis
	g.DATA.UserInfo.InitUserInfo(_userInfo)

	// 注册送
	_prize := []*cfg.Gameatn{
		{A: "hero", T: "11001", N: 1},
		{A: "hero", T: "11002", N: 1},
		{A: "hero", T: "11003", N: 1},
		{A: "item", T: "10001", N: 10},
		{A: "item", T: "10002", N: 2},
		{A: "item", T: "10003", N: 10},
		{A: "attr", T: "jinbi", N: 10000},
	}
	g.GetPrizeRes(
		_uid,
		_prize,
		map[string]any{"act": "注册送奖励"},
		gatewayUrl,
		false,
	)

	return _userInfo

}

// GetUserInfoByWhere 通过条件查询玩家
func (m *ModuleUser) GetUserInfoByWhere(where bson.M) *pb.ModelUser {
	_userInfo := &pb.ModelUser{}
	g.Mdb.FindOneByReflect("userinfo", where, _userInfo)
	return _userInfo
}
